﻿'use strict'
let mysql = require("mysql");
let dbConfig = require("../../main/app.config").mysqlConfig;


let queryFormat = function (query, values) {
    if (!values) return query;
    return query.replace(/\:(\w+)/g, function (txt, key) {
        if (values.hasOwnProperty(key)) {
            return this.escape(values[key]);
        }
        return txt;
    }.bind(this));
};

let log_mysql = function (sql, vals) {
    let fullSql = "";
    if (!vals) {
        vals = {};
    }
    fullSql = "mysql:    " + sql + "\n" + JSON.stringify(vals);


    fullSql = (fullSql.replace(/\n/ig, "\n          "));
    console.log(fullSql);
};

//记得最后  conn.release();
let getConn = async () => {
    try {
        let pool = mysql.createPool(dbConfig);
        if (!pool) return console.error("mysql pool Error:" + err);

        return new Promise(function (resolve, reject) {
            return pool.getConnection(function (err, conn) {
                if (err) {
                    console.error(err);
                    resolve(null);
                    return;
                }
                resolve(conn);
            });
        });
    }
    catch (err) {
        console.error("mysql connecte Error:" + err);
        throw err;
        return;
    }
};

let ops = {
//自动释放连接
    async exec(sql, vals) {
        if (!sql) return;
        log_mysql(sql, vals);

        let db = await getConn();
        if (!db) return console.error("获取连接失败");


        if (sql.startsWith("select")) {
            db.config.queryFormat = queryFormat;
        }

        try {
            //return  pool.query(sql,vals);
            return new Promise(function (resolve, reject) {
                return db.query(
                    sql,
                    vals, function (err, res) {
                        db.release();
                        if (err) {
                            console.error(err);

                            reject(err);
                            return;
                        }
                        resolve(res);
                    });
            });
        }
        catch (err) {
            db.release();
            console.error("mysql Error:" + err);

            throw err;
            return;
        }
    },

    async findOne(sql, vals) {
        let result = await exec(sql, vals);
        return result && result[0];
    },
//插入数据，可以是多条，但以第一条数据的列为标准
    async insert(table, data) {
        let datas = [];
        if (Array.isArray(data)) {
            datas = data;
        }
        else {
            datas.push(data);
        }

        if (!datas.length) {
            return {affectedRows: 0, msg: "找不到要插入的数据"};
        }

        let keys = [];
        for (let k in datas[0]) {
            keys.push(k);
        }
        let vals_temp = "(" + keys.map(it => "?").join(",") + ")";
        let sql = "insert into `" + table + "` (" + keys.map(it => "`" + it + "`").join(",") + ") values " + datas.map(it => vals_temp);
        let vals = [];
        for (let item of datas) {
            vals = vals.concat(keys.map(key => item[key]));
        }

        return await exec(sql, vals);
    }
};

ops.find = ops.exec;

Object.assign(exports, ops)

